package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.common.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Override
    public ResponseResult findNewsByPage(WmNewsPageReqDto dto) {
        dto.checkParam();

        IPage page=new Page(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<WmNews> wmNewsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            wmNewsLambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        if (dto.getChannelId()!=null){
            wmNewsLambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        if (dto.getBeginPubDate()!=null&&dto.getEndPubDate()!=null){
            wmNewsLambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        if (StringUtils.isNotBlank(dto.getKeyword())){
            wmNewsLambdaQueryWrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        wmNewsLambdaQueryWrapper.orderByDesc(WmNews::getCreatedTime);
        //获取当前登录人的文章
        wmNewsLambdaQueryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getWmUser().getId());
        page=page(page,wmNewsLambdaQueryWrapper);
        ResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());


        return result;
    }

    @Override
    @Transactional
    public ResponseResult submit(WmNewsDto wmNewsDto) throws Exception {
        if (wmNewsDto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (wmNewsDto.getType()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //属性拷贝
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto,wmNews);
        String imgStr = StringUtils.join(wmNewsDto.getImages(), ",");
        wmNews.setImages(imgStr);
        wmNews.setUserId(WmThreadLocalUtil.getWmUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable((short) 1);
        if (wmNewsDto.getType()==-1){
            wmNews.setType(null);
        }

        if (wmNewsDto.getId()==null){
            //保存
            wmNewsMapper.insert(wmNews);
        }else {
            //删除文章和素材之间的对应关系
            wmNewsMaterialMapper.delete(new LambdaQueryWrapper<WmNewsMaterial>().eq(WmNewsMaterial::getNewsId,wmNewsDto.getId()));
            //修改文章内容
            wmNewsMapper.updateById(wmNews);
        }
        //如果是草稿，直接结束方法
        if (wmNewsDto.getStatus()==0){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        List<String> imageList = new ArrayList<>();
        //如果是发布的话，保存文章和素材的对应关系
        String content = wmNewsDto.getContent();
        JSONArray imageArr = JSON.parseArray(content);
        for (int i = 0; i < imageArr.size(); i++) {
            JSONObject image = imageArr.getJSONObject(i);
            //如果json中的key为图片的话
            if ("image".equals(image.getString("type"))){
                String value = image.getString("value");
                WmMaterial wmMaterial = wmMaterialMapper.selectOne(new LambdaQueryWrapper<WmMaterial>().eq(WmMaterial::getUrl, value));
                if (wmMaterial==null){
                    throw new CustomException(AppHttpCodeEnum.IMAGE_DELETE);
                }
                imageList.add(value);
                Integer wmMaterialId = wmMaterial.getId();//素材id
                Integer wmNewsId = wmNews.getId();//文章id
                WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
                wmNewsMaterial.setNewsId(wmNewsId);
                wmNewsMaterial.setMaterialId(wmMaterialId);
                wmNewsMaterial.setType((short) 0);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            }
        }

        //如果不是草稿，且封面类型选自动的时候，还需要保存封面图片与文章的关系
        saveCoverImageWithNews(wmNewsDto.getType(),wmNews,imageList);
        //wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        wmNewsTaskService.addNewsToTask(wmNews.getId(),wmNews.getPublishTime());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }

    /**
     * 自媒体上下架
     * @param wmNewsDto
     * @return
     */
    @Override
    public ResponseResult DownOrUp(WmNewsDto wmNewsDto) {
        Integer id = wmNewsDto.getId();
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if (wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章未发布，无法上下架");
        }
        Integer enable = wmNewsDto.getEnable();
        if (enable==0){
            wmNews.setEnable((short) 0);
        }
        if (enable==1){
            wmNews.setEnable((short) 1);
        }

        wmNewsMapper.updateById(wmNews);
        kafkaTemplate.send("weNews-topic",JSON.toJSONString(wmNews));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //
    private void saveCoverImageWithNews(Short type, WmNews wmNews, List<String> imageList) {
        //当封面类型为自动时
        if (type==-1){
            if (imageList.size()>=3){
                wmNews.setType((short) 3);
                List<String> listThree = imageList.stream().limit(3).collect(Collectors.toList());
                String imagesThree = StringUtils.join(listThree, ",");
                wmNews.setImages(imagesThree);
            }else if (!imageList.isEmpty() &&imageList.size()<3){
                wmNews.setType((short) 1);
                List<String> listOne = imageList.stream().limit(1).collect(Collectors.toList());
                String imagesOne = StringUtils.join(listOne, ",");
                wmNews.setImages(imagesOne);
            }else {
                wmNews.setType((short) 0);

            }

            wmNewsMapper.updateById(wmNews);
        }

        //保存封面和文章的关系

        for (String image : imageList) {
            WmMaterial wmMaterial = wmMaterialMapper.selectOne(new LambdaQueryWrapper<WmMaterial>()
                    .eq(WmMaterial::getUrl,image));
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(wmMaterial.getId());
            wmNewsMaterial.setNewsId(wmNews.getId());
            wmNewsMaterial.setType((short) 1);
            wmNewsMaterialMapper.insert(wmNewsMaterial);
        }


    }
}
